<?php
namespace app\index\logic;

use app\index\model\UserModel;
use EasyWeChat\Foundation\Application;
use think\Session;

class UserLogic
{
    public function update_user($info){
        $model = new UserModel();
        $user = $model->where(['openid'=>$info['openid']])->find();
        $data = [];
        $data['nickname'] = $info['nickname'];
        $data['headimgurl'] = $info['headimgurl'];
        $data['sex'] = $info['sex'];
        if($user){
            $where = [];
            $where['openid'] = $info['openid'];
            $data['update_time'] = time();
            $user->isUpdate(true)->save($data,$where);
        }else{
            $data['openid'] = $info['openid'];
            $data['update_time'] = time();
            $data['add_time'] = time();
            $model->isUpdate(false)->save($data);
        }
        $info = $model->where(['openid'=>$info['openid']])->find()->toArray();
        $this->set_user_info($info);
    }
    public function check_user(){
        $info = $this->get_user_info();
        if($info === false){
            return false;
        }else{
            return $info;
        }
    }

    /**
     * 获取用户信息
     * @return bool|mixed
     */
    private function get_user_info(){
        $info = Session::get('user_info');
        if(isset($info) === false){
            return false;
        }else{
            return $info;
        }
    }

    /**
     * 设置用户登录状态
     * @return bool|mixed
     */
    private function set_user_info($info){
        Session::set('user_info.user_id',$info['id']);
        Session::set('user_info.nickname',$info['nickname']);
        Session::set('user_info.headimgurl',$info['headimgurl']);
        Session::set('user_info.openid',$info['openid']);
        $result = strtotime($info['update_time']);
        if($result){
            Session::set('user_info.update_time',strtotime($info['update_time']));
        }else{
            Session::set('user_info.update_time',$info['update_time']);
        }
    }

    /**
     * 获取用户信息
     * @return bool|mixed
     */
    public static function user_info(){
        $info = Session::get('user_info');
        return $info;
    }
}
